package com.lan.parse;

import com.lan.ScriptContext;
import com.lan.antlr.ScriptBaseListener;
import com.lan.antlr.ScriptParser;
import com.lan.model.Tv;
import com.lan.model.Type;
import com.lan.model.Variable;
import com.lan.model.symbol.*;
import com.lan.util.ParseUtils;

import java.util.List;

public class VarListener extends ScriptBaseListener {

    private ScriptContext context;

    public VarListener(ScriptContext context) {
        this.context = context;
    }

    @Override
    public void enterExpression(ScriptParser.ExpressionContext ctx) {
        if (ctx.json() == null && ctx.function() == null) {
            return;
        }
        Scope scope = context.nodeOfScope(ctx);
        //第一层 scope
        List<Tv> nameList = ParseUtils.getNameList(ctx.propertysExp());
        String varName = Tv.toString(nameList, "_");
        Variable variable = context.lookupVariable(scope, varName);
        if (variable == null) {
            variable = new Variable(scope.getId() + "_" + varName, varName, scope, null);
        }
        if (ctx.json() != null) {
            Json json = context.lookupJson(scope, varName);
            if (ctx.json().obj() != null) {
                variable.setType(Type.JSON);
                variable.setValue(json);
            } else if (ctx.json().arr() != null) {
                variable.setType(Type.JArray);
                variable.setValue(json);
            }
        } else if (ctx.function() != null) {
            variable.setType(Type.Function);
            Function function = context.lookupFunction(scope, varName);
            variable.setValue(function);
        }
        scope.add(variable);
    }


}
